var $utils = $('utils').extend({
	myName: "$('$utils')",
	parameters: [],
	log: function(e){
		if($utils.parameters['debug']){
			if(!console.log){//TODO:append body code.
				window.alert(e);
				return;
			}
			console.log(e);
		}
	},
	getParametersFromURL: function(url){
		if (url.match(/https?[^?]+\?([^#]*)/)) {
			var q = RegExp.$1;
			var a = q.split('&')
			for (var n in a) {
				if (a[n].match(/^([^=]+)=(.*)$/)) {
					$utils.parameters[RegExp.$1] = decodeURIComponent(RegExp.$2);
				}
			}
			//finish.
			if($utils.parameters['debug']){
				var s = $utils.myName+'.parameters:[';
				for(var i in $utils.parameters){
					s=s+'"'+i+'",';
				}
				s=s.slice(0,-1)+']';
				console.log(s);
			}
			$utils.log($utils.myName+'.getParametersFromURL():');
		}
	}
});
$(function(){
	$utils.getParametersFromURL(location.href);
});

var $jsonengine = $('jsonengine').extend({
	myName: "$('$jsonengine')",
	log: window.alert,
	docType: '',
	filter: '',
	_ajax: function(success, error){
		$jsonengine.log($jsonengine.method+' '+$jsonengine.uri);
		$.ajax({
			url    : $jsonengine.uri,
			type   : $jsonengine.method,
			success: success,
			error  : error
		});
	},
	_get: function(success, error){
		$jsonengine.uri = '/_je/' + $jsonengine.docType + $jsonengine.filter;
		$jsonengine.method = 'GET';
		$jsonengine._ajax(success, error);
		//finish.
		$jsonengine.log($jsonengine.myName+'._get():');
	},
	_post: function(success, error){
		$jsonengine.uri = '/_je/' + $jsonengine.docType + '?' + $jsonengine.filter;
		$jsonengine.method = 'POST';
		$jsonengine._ajax(success, error);
		//finish.
		$jsonengine.log($jsonengine.myName+'._post():');
	},
	_put: function(success, error){
		$jsonengine.uri = '/_je/' + $jsonengine.docType + '?' + $jsonengine.filter;
		$jsonengine.method = 'PUT';
		$jsonengine._ajax(success, error);
		//finish.
		$jsonengine.log($jsonengine.myName+'._put():');
	},
	_delete: function(success, error){
		$jsonengine.uri = '/_je/' + $jsonengine.docType;// + '/' + $jsonengine.filter;
		$jsonengine.method = 'DELETE';
		$jsonengine._ajax(success, error);
		//finish.
		$jsonengine.log($jsonengine.myName+'._delete():');
	}
});
$(function(){
	if($utils){
		$jsonengine.log = $utils.log;
		if($utils.parameters['docType'])
			$jsonengine.docType = $utils.parameters['docType'];
	}
});

var $jeviewer = $('jeviewer').extend({
	myName: "$('$jeviewer')",
	log: window.alert,
	docType: '',
	je: {},
	help: function(){
		//TODO
		$('body').append('TODO:セットアップ手順を書く');
		//finish.
		$jeviewer.log($jeviewer.myName+'.help(): 0');
		return 0;
	},
	createDOM: function(){
		//title
		$('title').append('jsonengine data viewer');
		//style
		var css = $('<style type="text/css"/>')
			.append('#filter{width:100%;}')
			.append('#data input{width:100%;cursor:pointer;}')
			.append('#_CLEAR{margin-left:1em;}')
			.append('.err strong{color:red;}')
			;
		var head = $('head');
		head.append(css);
		//script
		var js = $('<script type="text/javascript" src="jkl-dumper.js"/>');
		head.append(js);
		//body
		var body = $('body');
		body.append($('<h1/>').append($jeviewer.docType));
		body.append($('<textarea id="filter"/>'));
		body.append($('<button id="_GET"/>').append('GET'));
		body.append($('<button id="_CLEAR"/>').append('CLEAR'));
		body.append($('<br/>'));
		body.append($('<br/>'));
		body.append($('<button id="_POST"/>').append('POST'));
		body.append($('<button id="_PUT"/>').append('PUT'));
		body.append($('<button id="_DELETE"/>').append('DELETE'));
		body.append($('<p id="status"/>').append('status:'));
		body.append($('<p id="data"/>'));
		//finish.
		$jeviewer.log($jeviewer.myName+'.createDOM():');
	},
	bindObjects: function(){
		$jeviewer.$filter = $('#filter');
		$jeviewer.$status = $('#status');
		$jeviewer.$data   = $('#data');
		$jeviewer.$clear  = $('#_CLEAR');
		$jeviewer.$get    = $('#_GET');
		$jeviewer.$post   = $('#_POST');
		$jeviewer.$put    = $('#_PUT');
		$jeviewer.$delete = $('#_DELETE');
		//finish.
		$jeviewer.log($jeviewer.myName+'.bindObjects():');
	},
	setEvents: function(){
		var checkBefore = {
			_get: function() {
				$jeviewer.je.filter = $jeviewer.$filter.val().trim();
				//finish.
				$jeviewer.log($jeviewer.myName+'.setEvents.checkBefore._get():');
				return 1;
			},
			_post: function() {
				if($jeviewer.$filter.val().trim()=='')
					return confirm('パラメータは空です。空のデータを作成しますか？')? 1:0;
				$jeviewer.je.filter = $jeviewer.$filter.val().trim();
				//finish.
				$jeviewer.log($jeviewer.myName+'.setEvents.checkBefore._post():');
				return 1;
			},
			_put: function() {
				if($jeviewer.$filter.val().trim()=='')
					return alert('パラメータは空です。');
				$jeviewer.je.filter = $jeviewer.$filter.val().trim();
				//finish.
				$jeviewer.log($jeviewer.myName+'.setEvents.checkBefore._put():');
				return 1;
			},
			_delete: function() {
				if($jeviewer.$filter.val().trim()=='')
					return confirm('パラメータは空です。全権削除しますか？')? 1:0;
				$jeviewer.je.filter = $jeviewer.$filter.val().trim();
				//finish.
				$jeviewer.log($jeviewer.myName+'.setEvents.checkBefore._delete():');
				return 1;
			}
		};
		var createList = function(json, status, xhr){
			c=0;
			for(var i in json){
				c++;
			}
			console.log('LIST SIZE IS:'+c)
			updateStatus(xhr);
			$jeviewer.$data.empty();
			var dumper = new JKL.Dumper();
			var createForm = function(o) {
				var form = $('<p/>');
				for (var k in o) 
					form.append($('<p/>').append($('<p/>').append(k + ':' + o[k])));
				return form;
			};
			var createElement = function(o){
				$jeviewer.log(o);
				var i = $('<input class="expand"/>').click(function(){
					if(i.attr('class')){
						i.attr('class', null);
						i.after(createForm(o));
					}else{
						i.attr('class', 'expand');
						$(this.parentNode.childNodes[1]).remove();
					}
				});
//				var d = $('<div/>').append(i.val(uneval(o).slice(1, -1) || ''));//文字化け対策が必要
				var d = $('<div/>').append(i.val(dumper.dump(o) || ''));//文字化け対策が必要
				$('#data').append(d);
			};
			if(Object.prototype.toString.call(json)=='[object Array]'){
				$.each(json, function(){
					var o = this;
					createElement(o);
				});
			}
			else if(Object.prototype.toString.call(json)=='[object Object]'){
				createElement(json);
			}
			//finish.
			$jeviewer.log($jeviewer.myName+'.setEvents.createList():');
		};
		var errorMessage = function(xhr, status){
			updateStatus(xhr);
			$jeviewer.$data.empty();
			//finish.
			$jeviewer.log($jeviewer.myName+'.setEvents.errorMessage():');
		};
		var updateStatus = function(xhr){
			$jeviewer.$status.text('');
			var d = new Date();
			$jeviewer.$status.append(d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());
			var url = location.protocol + '//' + location.host + $jeviewer.je.uri;
			$jeviewer.$status.append($('<strong/>').append(' ' + $jeviewer.je.method + ' ' + url));
			var s = $('<span/>').append(' status:' + xhr.status);
			(xhr.status!=200)? $jeviewer.$status.attr('class','err'):$jeviewer.$status.attr('class','');
			$jeviewer.$status.append(s);
			//finish.
			$jeviewer.log($jeviewer.myName+'.setEvents.updateStatus():');
		};
		$jeviewer.$get.click(function(){
			if(!checkBefore._get())return;
			$jeviewer.je._get(createList, errorMessage);
			//finish.
			$jeviewer.log($jeviewer.myName+'.setEvents.$get.click():');
		});
		$jeviewer.$post.click(function(){
			if(!checkBefore._post())return;
			$jeviewer.je._post(createList, errorMessage);
			//finish.
			$jeviewer.log($jeviewer.myName+'.setEvents.$post.click():');
		});
		$jeviewer.$put.click(function(){
			if(!checkBefore._put())return;
			$jeviewer.je._put(createList, errorMessage);
			//finish.
			$jeviewer.log($jeviewer.myName+'.setEvents.$put.click():');
		});
		$jeviewer.$delete.click(function(){
			if(!checkBefore._delete())return;
			$jeviewer.je._delete(createList, errorMessage);
			//finish.
			$jeviewer.log($jeviewer.myName+'.setEvents.$delete.click():');
		});
		$jeviewer.$clear.click(function(){
			$jeviewer.$filter.val('');
			//finish.
			$jeviewer.log($jeviewer.myName+'.setEvents.$clear.click():');
		});
		//finish.
		$jeviewer.log($jeviewer.myName+'.setEvents.setEvents():');
	}
});
$(function(){
	if($utils){
		if(!$utils.parameters['docType']) return $jeviewer.help();
		$jeviewer.log = $utils.log;
		$jeviewer.docType = $utils.parameters['docType'];
	}
	if($jsonengine){
		$jeviewer.je = $jsonengine;
	}
	$jeviewer.createDOM();
	$jeviewer.bindObjects();
	$jeviewer.setEvents();
});

$(function(){
});
